package com.alibaba.middleware.hsf.guide.framer;

import com.taobao.hsf.io.ByteBufferWrapper;
import com.taobao.hsf.io.common.BytesUtil;

import java.util.LinkedList;

/**
 * @author weipeng2k 2018年04月09日 上午10:14:20
 */
public class TestByteBuf implements ByteBufferWrapper {

    LinkedList<Byte> content = new LinkedList<Byte>();

    int pos;

    @Override
    public void writeByte(int index, byte data) {
        content.set(index, data);
    }

    @Override
    public void writeByte(byte data) {
        content.add(data);
    }

    @Override
    public byte readByte() {
        try {
            return content.pop();
        } finally {
            pos++;
        }
    }

    @Override
    public void writeInt(int data) {
        for (byte b : BytesUtil.int2bytes(data)) {
            content.add(b);
        }
    }

    @Override
    public void writeBytes(byte[] data) {
        for (byte datum : data) {
            content.add(datum);
        }
    }

    @Override
    public int readableBytes() {
        return content.size();
    }

    @Override
    public int readInt() {
        byte[] ints = new byte[4];
        ints[0] = readByte();
        ints[1] = readByte();
        ints[2] = readByte();
        ints[3] = readByte();

        return BytesUtil.bytes2int(ints);
    }

    @Override
    public void readBytes(byte[] dst) {
        for (int i = 0; i < dst.length; i++) {
            dst[i] = readByte();
        }
    }

    @Override
    public int readerIndex() {
        return pos;
    }

    @Override
    public void setReaderIndex(int readerIndex) {
        pos = readerIndex;
    }

    @Override
    public void writeLong(long id) {
        for (byte b : BytesUtil.long2bytes(id)) {
            content.add(b);
        }
    }

    @Override
    public long readLong() {
        byte[] longs = new byte[8];
        longs[0] = readByte();
        longs[1] = readByte();
        longs[2] = readByte();
        longs[3] = readByte();
        longs[4] = readByte();
        longs[5] = readByte();
        longs[6] = readByte();
        longs[7] = readByte();
        return BytesUtil.bytes2long(longs);
    }

    @Override
    public void ensureCapacity(int capacity) {

    }

    @Override
    public void clear() {
        content.clear();
    }
}
